﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CprExam.Model;
using GalaSoft.MvvmLight.Command;
using GLCommon;
using Newtonsoft.Json.Linq;

namespace CprExam.ViewModel
{
    public class LoginViewModel:VmBase
    {
        public RelayCommand SubmitCommand { get; private set; }
        private string _clientName;
        public string ClientName
        {
            get { return _clientName; }
            set
            {
                _clientName = value;
                RaisePropertyChanged("ClientName");
            }
        }

        public LoginViewModel()
        {
            SubmitCommand = new RelayCommand(SubmitExec);
            ClientName = GetClientName();
            if (!String.IsNullOrEmpty(ClientName))
                Login();
        }

        private async void SubmitExec()
        {
            await Login();
        }

        private async Task Login()
        {
            string serial = GetSerial();
            LogTool.WriteInfoLog("Login serial:" + serial);
            string url = $"Login?name={ClientName}&password={serial}";

            try
            {
                var result = await HttpTool.PostAsJsonAsync(url, null);
                if (result == null)
                {
                    Send<string>("服务器连接失败，请联系客服", MessageToken.LoginFail);
                    return;
                }
                var jdata = JObject.Parse(result);
                if (jdata["status"] != null)
                {

                    int status = (int)jdata["status"];

                    if (status == 0)
                    {
                        HttpTool.Session = (string)jdata["session"];
                        SaveClientName();
                        LogTool.UpServerLog("客户端登录：" + serial, EventType.Information);
                        Send(MessageToken.LoginSuccess);
                    }
                    else if (status == 1)
                    {
                        Send<string>("单位名称不存，请联系客服", MessageToken.LoginFail);
                    }
                    else if (status == 2)
                    {
                        Send<string>("密码错误，请联系客服", MessageToken.LoginFail);
                    }
                    else
                    {
                        Send<string>("未知错误，请联系厂家客服", MessageToken.LoginFail);
                    }
                }

            }
            catch (Exception ex)
            {
                string message = string.Empty;
                GetMessage(ex, ref message);
                MessageBox.Show(message, "提示", MessageBoxButton.OK);
            }


        }

        string GetClientName()
        {
            string value = "";
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = config.AppSettings.Settings;
                var item = settings["ClientName"];
                if (item == null)
                {
                    config.AppSettings.Settings.Add("ClientName", "");
                }
                else
                {
                    value = item.Value;
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex.Message, ex);
            }

            return value;
        }



        private void SaveClientName()
        {
            Global.ClientName = ClientName;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["ClientName"].Value = this.ClientName;
            config.Save();
        }
    }
}
